package com.dajie.pt.controller.edm;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.dajie.common.DictionaryServicesContext;
import com.dajie.common.dictionary.DictEnum;
import com.dajie.common.dictionary.model.Dict;
import com.dajie.common.dictionary.service.DictService;
import com.dajie.common.framework.spring.controller.BaseController;
import com.dajie.corp.api.CorpServicesContext;
import com.dajie.corp.api.service.CorpService;
import com.dajie.corpreview.api.model.CorpreviewReviewDetail;
import com.dajie.corpreview.api.service.CorpReviewApiService;
import com.dajie.corpreview.client.CorpReviewServiceFactory;
import com.dajie.infra.user.model.UserBase;
import com.dajie.pt.model.EdmCorpReviewInfo;
import com.dajie.pt.service.EdmCorpReviewService;

@Controller
@RequestMapping("/edm")
public class EdmController extends BaseController {

    protected static final Logger LOGGER = LoggerFactory.getLogger(EdmController.class);

    CorpService corpService = CorpServicesContext.getInstance().getCorpService();
    CorpReviewApiService corpReviewApiService = CorpReviewServiceFactory.getInstance().getCorpReviewApiService();

    static DictService dictService = DictionaryServicesContext.getInstance().getDictService();

    static Dict dictCity = dictService.getDict(DictEnum.DICT_CITY);

    static Dict dictSalary = dictService.getDict(DictEnum.DICT_SALARY);
    private final static int flag = 0;

    @Autowired
    EdmCorpReviewService<EdmCorpReviewInfo, Integer> edmCorpReviewService;


    @RequestMapping("index")
    public ModelAndView index(HttpServletRequest request,
                              HttpServletResponse response,
                              @RequestParam(value = "corpid", required = true) Integer corpId,
                              @RequestParam(value = "uid", required = true) Integer uid,
                              @RequestParam(value = "status", required = true) Integer status) {

        LOGGER.info("====================" + this.getClass().getSimpleName());

        UserBase userBase = this.getLoginUser();
        if (userBase != null) {
            uid = userBase.getUid();
        }
        ModelAndView mv = null;
        String userAgent = request.getHeader("User-Agent");
        if (userAgent.contains("Android") || userAgent.contains("iPhone")) {
            mv = new ModelAndView("edm/index_mobile");
        } else {
            mv = new ModelAndView("edm/index");
        }


        long st = System.currentTimeMillis();
        long scoreSum = 0;
        long impressionCareerSum = 0;
        long impressionSkillSum = 0;
        long impressionAtmosSum = 0;
        long impressionPressureSum = 0;
        long impressionProspectSum = 0;
        int flag = 0;
        EdmCorpReviewInfo edmCorpReviewInfo = null;
        Map<String, Object> map = new HashMap<String, Object>();
        String corpName = corpService.getCorpBaseById(corpId).getName();
        EdmCorpReviewInfo edmCorpReviewInfo1 = edmCorpReviewService.getEdmCorpReviewByCorpId(corpId, flag);
        if (edmCorpReviewInfo1 != null) {
            if (status == 0) {
                edmCorpReviewService.updateEdmCorpReviewYesByCorpId(corpId, flag);
            } else {
                edmCorpReviewService.updateEdmCorpReviewNoByCorpId(corpId, flag);
            }
            edmCorpReviewInfo = edmCorpReviewService.getEdmCorpReviewByCorpId(corpId, flag);
        } else {
            edmCorpReviewService.insertEdmCorpReviewNumByCorpId(corpId, flag);
            if (status == 0) {
                edmCorpReviewService.updateEdmCorpReviewYesByCorpId(corpId, flag);
            } else {
                edmCorpReviewService.updateEdmCorpReviewNoByCorpId(corpId, flag);
            }
            edmCorpReviewInfo = edmCorpReviewService.getEdmCorpReviewByCorpId(corpId, flag);
        }
        CorpreviewReviewDetail reviewDetail = null;
        List<CorpreviewReviewDetail> list = corpReviewApiService.getReviewList(
                corpId, 1, 0, 1);
        //得到第一条评论
        if (list != null && !list.isEmpty()) {
            reviewDetail = list.get(0);
            if (reviewDetail.getCommentCorp().substring(0, 6).equals("#离职原因#")) {
                reviewDetail.setCommentCorp(reviewDetail.getCommentCorp().substring(6));
            }
        } else {
            flag = 1;
        }
        //得到公司初始评价
        map = corpReviewApiService.getCorpReviewMap(corpId);
        if (map != null && map.size() > 0) {
            if ((Integer) map.get("code") == 1) {
                scoreSum = Math.round((Double) map.get("scoreSum") * 5);
                impressionCareerSum = Math.round((Double) map.get("impressionCareerSum") * 5);
                impressionSkillSum = Math.round((Double) map.get("impressionSkillSum") * 5);
                impressionAtmosSum = Math.round((Double) map.get("impressionAtmosSum") * 5);
                impressionPressureSum = Math.round((Double) map.get("impressionPressureSum") * 5);
                impressionProspectSum = Math.round((Double) map.get("impressionProspectSum") * 5);

            } else {
                scoreSum = this.getRandomNum();
                impressionCareerSum = this.getRandomNum();
                impressionSkillSum = this.getRandomNum();
                impressionAtmosSum = this.getRandomNum();
                impressionPressureSum = this.getRandomNum();
                impressionProspectSum = this.getRandomNum();
            }
        }


        mv.addObject("corpName", corpName);
        mv.addObject("reviewDetail", reviewDetail);
        mv.addObject("corpId", corpId);
        mv.addObject("scoreSum", scoreSum);
        mv.addObject("impressionCareerSum", impressionCareerSum);
        mv.addObject("impressionSkillSum", impressionSkillSum);
        mv.addObject("impressionAtmosSum", impressionAtmosSum);
        mv.addObject("impressionPressureSum", impressionPressureSum);
        mv.addObject("impressionProspectSum", impressionProspectSum);
        mv.addObject("edmCorpReviewInfo", edmCorpReviewInfo);
        mv.addObject("uid", uid);
        mv.addObject("status", status);
        mv.addObject("flag", flag);
        LOGGER.info("EdmController.index.timecost:{}", (System.currentTimeMillis() - st));
        return mv;
    }

//    private void convertDict(SimpleJob simpleJob) {
//        if (StringUtils.isNotEmpty(simpleJob.getCity())) {
//            simpleJob.setCity(dictCity.getNamesByIds(simpleJob.getCity()));
//        }
//        if (StringUtils.isNotEmpty(simpleJob.getSalary())) {
//            simpleJob.setSalary(dictSalary.getNamesByIds(simpleJob.getSalary()));
//        }
//        if (StringUtils.isNotEmpty(simpleJob.getSalaryEnd())) {
//            simpleJob.setSalaryEnd(dictSalary.getNamesByIds(simpleJob.getSalaryEnd()));
//        }
//    }

    private int getRandomNum() {
        Random rd = new Random();//随机数生成器
        return (int) (rd.nextDouble() * 2) + 4;
    }

    @RequestMapping("corpReview")
    public ModelAndView corpReview(HttpServletRequest request,
                                   HttpServletResponse response,
                                   @RequestParam(value = "statuses", required = true) Integer status,
                                   @RequestParam(value = "reason", required = true) String reason,
                                   @RequestParam(value = "uid", required = true) Integer uid,
                                   @RequestParam(value = "corpId", required = true) Integer corpId,
                                   @RequestParam(value = "impression", required = true) int impressionCorpScore,
                                   @RequestParam(value = "agree", required = true) int impressionCeoScore,
                                   @RequestParam(value = "career", required = true) int career,
                                   @RequestParam(value = "skill", required = true) int skill,
                                   @RequestParam(value = "workAtmos", required = true) int workAtmos,
                                   @RequestParam(value = "workPressure", required = true) int workPressure,
                                   @RequestParam(value = "prospect", required = true) int prospect
    ) {

        UserBase userBase = this.getLoginUser();
        if (userBase != null) {
            uid = userBase.getUid();
        }

        int isMember = 2;
        int isAnonymous = 0;
        String topic = "#离职原因#";
        String reasonTopic = topic + reason;
        StringBuffer sbf = new StringBuffer(reasonTopic);
        for (int i = 0; i <= (20 - reasonTopic.length()); i++) {
            sbf.append(" ");
        }
        String reviewContent = sbf.toString();
        //String reviewContent=reason.trim();
        EdmCorpReviewInfo edmCorpReviewInfo = edmCorpReviewService.getEdmCorpReviewByCorpId(corpId, flag);
        CorpreviewReviewDetail corpReviewDetail = null;
        Map<String, Object> corpReviews = corpReviewApiService.addCorpReview(uid, corpId, isMember, impressionCorpScore, impressionCeoScore, isAnonymous, null, reviewContent);
        int[] impressions = {career, skill, workAtmos, workPressure, prospect};
        Integer reviewId = null;
        if ((Integer) corpReviews.get("code") == 0) {
            reviewId = (Integer) corpReviews.get("reviewId");
        }

        corpReviewApiService.impressionSave(uid, corpId, reviewId, impressions, reviewContent);
        List<Integer> idList = new ArrayList<Integer>();
        idList.add(reviewId);
        List<CorpreviewReviewDetail> reviewList = corpReviewApiService.getReviewListByIdList(idList);
        if (reviewList != null && !reviewList.isEmpty()) {
            corpReviewDetail = reviewList.get(0);
            if (corpReviewDetail.getCommentCorp().substring(0, 6).equals("#离职原因#")) {
                corpReviewDetail.setCommentCorp(corpReviewDetail.getCommentCorp().substring(6));
            }
        }
        String userAgent = request.getHeader("User-Agent");
        ModelAndView mv = null;
        if (userAgent.contains("Android") || userAgent.contains("iPhone")) {
            mv = new ModelAndView("edm/corpreview_mobile");
        } else {
            mv = new ModelAndView("edm/corpReview");
        }

        mv.addObject("status", status);
        mv.addObject("edmCorpReviewInfo", edmCorpReviewInfo);
        mv.addObject("reviewDetail", corpReviewDetail);
        mv.addObject("corpId", corpId);
        return mv;
    }
}

